package com.chendx.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.chendx.admin.feign.ArticleFeign;
import com.chendx.admin.feign.WemediaFeign;
import com.chendx.admin.mapper.AdChannelMapper;
import com.chendx.admin.mapper.AdSensitiveMapper;
import com.chendx.admin.service.WemediaNewsAutoScanService;
import com.chendx.common.aliyun.GreeTextScan;
import com.chendx.common.aliyun.GreenImageScan;
import com.chendx.common.fastdfs.FastDFSClient;
import com.chendx.model.admin.dtos.NewsAuthDto;
import com.chendx.model.admin.pojos.AdChannel;
import com.chendx.model.article.pojos.ApArticle;
import com.chendx.model.article.pojos.ApArticleConfig;
import com.chendx.model.article.pojos.ApArticleContent;
import com.chendx.model.article.pojos.ApAuthor;
import com.chendx.model.common.dtos.PageResponseResult;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.wemeida.pojos.WmNews;
import com.chendx.model.wemeida.pojos.WmUser;
import com.chendx.model.wemeida.vo.WmNewsVo;
import com.chendx.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * Created by chendx on 2022/3/4.
 */
@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private GreeTextScan greeTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${fdfs.url}")
    private String serverFilePath;
    @Autowired
    private AdSensitiveMapper adSensitiverMapper;
    @Autowired
    private AdChannelMapper adChannelMapper;
    @Autowired
    private RestHighLevelClient client;

    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        if (id == null) {
            log.error("当前的审核id空");
            return;
        }

        //1根据自媒体文章id查询文章信息
        WmNews wmNews = wemediaFeign.findById(id);
        if (wmNews == null) {
            log.error("审核的自媒体文章不存在，自媒体的id:{}", id);
            return;
        }
        //2.文章状态为4（人工审核通过）直接保存数据和创建索引
        if (wmNews.getStatus() == 4) {
            log.info("该自媒体文章需要人工审核: id = ", id);
            //保存数据
            saveAppArticle(wmNews);
            return;
        }
        //3.文章状态为8  发布时间小于等于当前时间 直接保存数据
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            log.info("该文章已审核，待发布：id = ", id);
            //保存数据
            saveAppArticle(wmNews);
            return;
        }
        //4.文章状态为1，待审核
        if (wmNews.getStatus() == 1) {
            //抽取文章内容中的纯文本和图片
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            //4.1 文本审核
            boolean handleTextScan = handleTextScan((String) contentAndImagesResult.get("content"), wmNews);
            if (!handleTextScan) return;
            //4.2 图片审核
            boolean handleImagesScan = handleImagesScan((List<String>) contentAndImagesResult.get("images"), wmNews);
            if (!handleImagesScan) return;
            //4.3 自管理的敏感词审核
            boolean sensitiveScanBoolean = handleSensitive((String) contentAndImagesResult.get("content"), wmNews);
            if (!sensitiveScanBoolean) return;
            //4.4 发布时间大于当前时间，
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()) {
                //修改文章状态为8
                updateWmNews(wmNews, (short) 8, "审核通过，待发布");
                return;
            }
        }
        //5.审核通过，修改自媒体文章状态为9  保存app端相关文章信息
        saveAppArticle(wmNews);
    }

    @Override
    public PageResponseResult findNews(NewsAuthDto dto) {

        PageResponseResult pageResult = wemediaFeign.findList(dto);
        pageResult.setHost(serverFilePath);
        return pageResult;
    }

    @Override
    public ResponseResult findOne(Integer id) {
        //1参数检查
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(serverFilePath);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        System.out.println(type +"  "+dto);
        //2.查询文章
        WmNews wmNews = wemediaFeign.findById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.审核没有通过
        if (type == 0){
            System.out.println("审核没有通过");
            updateWmNews(wmNews, (short) 2,dto.getMsg());
        }else if (type == 1){
            //4.人工审核通过
            System.out.println("审核通过");
            updateWmNews(wmNews,(short)4,"人工审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    private void saveAppArticle(WmNews wmNews) {
        //保存app文章
        ApArticle apArticle = saveArticle(wmNews);
        System.out.println("保存文章成功");
        //保存app文章配置
        saveArticleConfig(apArticle);
        System.out.println("保存app文章配置成功");
        //保存app文章内容
        saveArticleContent(apArticle, wmNews);
        System.out.println("保存app文章内容成功");

        //修改自媒体文章的状态为9
        System.out.println(apArticle.getId());
        wmNews.setArticleId(apArticle.getId());
        updateWmNews(wmNews, (short) 9, "审核通过");
        System.out.println("审核通过");

        //TODO es索引创建
        Map<String,Object> map = new HashMap();
        map.put("id",apArticle.getId().toString());
        map.put("publishTime",apArticle.getPublishTime());
        map.put("layout",apArticle.getLayout());
        map.put("images",apArticle.getImages());
        map.put("authorId",apArticle.getAuthorId());
        map.put("title",apArticle.getTitle());
        map.put("content",wmNews.getContent());

        IndexRequest indexRequest = new IndexRequest("app_article_info").id(wmNews.getArticleId().toString()).source(map);
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存文章
     *
     * @param wmNews
     * @return
     */
    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());

        //获取作者相关信息
        Integer wmUserId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findWmUserById(wmUserId.longValue());
        if (wmUser != null) {
            String wmUserName = wmUser.getName();
            ApAuthor apAuthor = articleFeign.selectAuthorByName(wmUserName);
            if (apAuthor != null) {
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }

        }

        //获取频道相关信息
        Integer channelId = wmNews.getChannelId();
        AdChannel channel = adChannelMapper.selectById(channelId);
        if (channel != null) {
            apArticle.setChannelId(channel.getId());
            apArticle.setChannelName(channel.getName());
        }

        return articleFeign.saveArticle(apArticle);
    }

    /**
     * 创建app端文章内容信息
     *
     * @param apArticle
     * @param wmNews
     */
    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);
    }

    /**
     * 创建app端文章配置信息
     *
     * @param apArticle
     */
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);

        articleFeign.saveArticleConfig(apArticleConfig);
    }

    /**
     * 提取文本内容和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        Map<String, Object> resultMap = new HashMap<>();
        String content = wmNews.getContent();
        List<Map> mapList = JSON.parseObject(content, List.class);
        StringBuffer textSb = new StringBuffer();
        List<String> images = new ArrayList<>();
        for (Map map : mapList) {
            if (map.get("type") != null && map.get("type").equals("text")) {
                textSb.append(map.get("value"));
            }
            if (map.get("type") != null && map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                images.add(imgUrl);
            }
        }
        if (wmNews.getType() != 0 && wmNews.getImages() != null) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        resultMap.put("content", textSb.toString());
        resultMap.put("images", images);
        return resultMap;
    }

    /**
     * 文本审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    public boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greeTextScan.greeTextScan(content);
            //审核不通过
            if (map != null && !map.get("suggestion").equals("pass")) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    updateWmNews(wmNews, (short) 2, "文章内容中有敏感词汇");
                    flag = false;
                }
                if (map.get("suggestion").equals("review")) {
                    updateWmNews(wmNews, (short) 3, "文章内容中有不确定词汇");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 审核图片
     *
     * @param imageUrls
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> imageUrls, WmNews wmNews) {
        boolean flag = true;
        if (imageUrls == null) {
            return flag;
        }
        try {
            List<byte[]> byteList = new ArrayList<>();
            for (String imageUrl : imageUrls) {
                imageUrl = imageUrl.replace(serverFilePath, "");
                int indexOf = imageUrl.indexOf("/");
                String groupName = imageUrl.substring(0, indexOf);
                String filePath = imageUrl.substring(indexOf + 1);
                byte[] bytes = fastDFSClient.download(groupName, filePath);
                byteList.add(bytes);
            }
            Map map = greenImageScan.imageScan(byteList);
            //审核不通过
            if (!map.get("suggestion").equals("pass")) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 2, "文章中图片有违规");
                    flag = false;
                }

                //人工审核
                if (map.get("suggestion").equals("review")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 3, "文章图片有不确定元素");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 敏感词审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        List<String> allSensitive = adSensitiverMapper.findAllSensitive();
        SensitiveWordUtil.initMap(allSensitive);
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if (resultMap.size() > 0) {
            log.error("敏感词过滤没有通过，包含了敏感词:{}", resultMap);
            //找到了敏感词，审核不通过
            updateWmNews(wmNews, (short) 2, "文章中包含了敏感词");
            flag = false;
        }
        return flag;
    }

    /**
     * 修改自媒体文章
     *
     * @param wmNews
     * @param status
     * @param msg
     */
    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        System.out.println(JSON.toJSONString(wmNews));
        wemediaFeign.updateWmNews(wmNews);
    }
}
